package com.example.myapplication.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.database.DatabaseHelper;
import com.example.myapplication.databinding.ActivityEditBinding;
import com.example.myapplication.model.Note;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class EditActivity extends AppCompatActivity {

    private ActivityEditBinding binding;
    private DatabaseHelper dbHelper;
    private Note currentNote; // 当前传递的笔记对象，区分新增和修改

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        dbHelper = new DatabaseHelper(this);

        // 接收传递的笔记对象，如果为空说明是新增
        Serializable noteSerializable = getIntent().getSerializableExtra("Note");
        if (noteSerializable != null) {
            currentNote = (Note) noteSerializable;
            binding.titleTv.setText("修改笔记ing");
            binding.contentEt.setText(currentNote.getContent());
            binding.titleEt.setText(currentNote.getTitle());
        } else {
            currentNote = null; // 新增模式
            binding.titleTv.setText("新建笔记ing");
        }

        // 返回按钮
        binding.backIv.setOnClickListener(view -> finish());
        // 调用初始化分类 Spinner
        initializeCategorySpinner();
        // 保存按钮
        binding.saveIV.setOnClickListener(view -> {
            String content = binding.contentEt.getText().toString().trim();
            String title = binding.titleEt.getText().toString().trim();

            String category = binding.categorySpinner.getSelectedItem().toString(); // 获取选中的分类

            // 获取分类ID
            int categoryId = dbHelper.getCategoryIdByName(category); // 根据分类名称获取分类ID

            if (title.isEmpty()) {
                title = "未命名笔记";
            }

            if (content.isEmpty()) {
                Toast.makeText(this, "内容不能为空！", Toast.LENGTH_SHORT).show();
                return;
            }

            if (category.equals("添加分类")) {
                Toast.makeText(this, "请选择一个有效分类！", Toast.LENGTH_SHORT).show();
                return;
            }

            if (currentNote != null) {
                // 更新笔记逻辑
                currentNote.setTitle(title);
                currentNote.setContent(content);

                // 更新笔记数据
                dbHelper.updateNote(currentNote);

                // 更新笔记分类
                dbHelper.updateNoteCategory(currentNote.getId(), categoryId);

                Toast.makeText(this, "笔记修改成功", Toast.LENGTH_SHORT).show();
            } else {
                // 新增笔记逻辑
                dbHelper.addNote(title, content, null, categoryId);
                Toast.makeText(this, "笔记保存成功", Toast.LENGTH_SHORT).show();
            }

            setResult(Activity.RESULT_OK);
            finish();
        });

        // 导出按钮的点击事件
        binding.exportIV.setOnClickListener(view -> {
            // 弹出选择导出类型的对话框
            showExportOptionsDialog();
        });

        // 清空按钮的点击事件
        binding.clearIV.setOnClickListener(v -> {
            binding.contentEt.setText(""); // 清空内容
            Log.d("EditActivity", "Clear button clicked");
        });
    }

    // 显示导出选项对话框
    private void showExportOptionsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择导出方式")
                .setItems(new CharSequence[] {"导出为图片", "导出为文本"},
                        (dialog, which) -> {
                            if (which == 0) {
                                exportNoteAsImage(); // 导出为图片
                            } else {
                                exportNoteAsText(); // 导出为文本
                            }
                        })
                .show();
    }

    // 导出笔记为图片
    private void exportNoteAsImage() {
        // 创建一个 Bitmap，大小为当前布局的宽高
        binding.getRoot().setDrawingCacheEnabled(true);
        binding.getRoot().buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(binding.getRoot().getDrawingCache());
        binding.getRoot().setDrawingCacheEnabled(false);
        // 保存图片到本地
        saveImageToGallery(bitmap);
    }

    // 保存图片到图库
    private void saveImageToGallery(Bitmap bitmap) {
        // 获取存储路径
        File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyNotes");
        if (!directory.exists()) {
            directory.mkdirs(); // 创建文件夹
        }

        // 创建文件名
        String fileName = "Note_" + System.currentTimeMillis() + ".png";
        File file = new File(directory, fileName);

        // 保存图片
        try (FileOutputStream fos = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            Toast.makeText(this, "笔记已导出为图片，保存在: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "导出失败，请重试！", Toast.LENGTH_SHORT).show();
        }

        // 刷新图库
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(Uri.fromFile(file));
        sendBroadcast(intent);
    }

    // 导出笔记为文本
    private void exportNoteAsText() {
        String content = binding.contentEt.getText().toString().trim();
        String title = binding.titleEt.getText().toString().trim();

        // 获取存储路径
        File directory = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "MyNotes/TextExports");
        if (!directory.exists()) {
            directory.mkdirs(); // 创建文件夹
        }

        // 检查是否创建了文件夹
        Log.d("Export", "Directory exists: " + directory.exists());

        // 创建文本文件
        String fileName = "Note_" + System.currentTimeMillis() + ".txt";
        File file = new File(directory, fileName);

        try (FileOutputStream fos = new FileOutputStream(file)) {
            String noteContent = "标题: " + title + "\n\n" + "内容: \n" + content;
            fos.write(noteContent.getBytes());
            fos.flush();
            Toast.makeText(this, "笔记已导出为文本，保存在: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
            Log.d("Export", "File saved at: " + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "导出失败，请检查存储权限或重试！", Toast.LENGTH_SHORT).show();
        }
    }



    // 初始化 Spinner
    private void initializeCategorySpinner() {
        List<String> categoryList = new ArrayList<>();
        // 获取所有分类
        List<String> categories = dbHelper.getAllCategories();
        categoryList.addAll(categories);

        Log.d("EditActivity", "Categories fetched: " + categoryList);

        // 创建 Spinner 的适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categoryList);
        binding.categorySpinner.setAdapter(adapter);
    }
}
